package org.gao.test.transaction.web.sample;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.sql.Connection;

public class TransactionInvocationHandler implements InvocationHandler{
	
	private Object object;
	
	public TransactionInvocationHandler(Object object) {
		this.object = object;
	}
	
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		Connection conn = ConnectionHolder.getConn();
		Object result = null;
		
		try {
			if(conn == null) {
				conn = ConnectionFactory.getConn();
			}
			
			System.out.println("conn = " + conn);
			
			ConnectionHolder.setConn(conn);
			conn.setAutoCommit(false);
			
			result = method.invoke(object, args);
			
			conn.commit();
		} catch (Throwable e) {
			e.printStackTrace();
			conn.rollback();
			throw e;
		} finally {
			conn.close();
		}
		return result;
		
	}

}
